package com.ssyc.gsk_teacher_appraisal.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.charts.RadarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.RadarData;
import com.github.mikephil.charting.data.RadarDataSet;
import com.github.mikephil.charting.data.RadarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IRadarDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.Constants;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.mapchart.PieChartManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.MathUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyListView;
import com.ssyc.gsk_teacher_appraisal.R;
import com.ssyc.gsk_teacher_appraisal.adapter.ContentLvAdapter;
import com.ssyc.gsk_teacher_appraisal.adapter.PieLvAdapter;
import com.ssyc.gsk_teacher_appraisal.bean.ContentInfo;
import com.ssyc.gsk_teacher_appraisal.bean.PieInfo;
import com.ssyc.gsk_teacher_appraisal.bean.TestInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 试卷分析界面
 * Created by Administrator on 2018/10/22 0022.
 */

public class TkTeacherAppraisalTestPaperActivity extends BaseActivity implements View.OnClickListener {
    private ImageView ivBack;

    //标题名称
    private TextView tvTitle;

    //平均分
    private TextView tvScore;

    //难易程度
    private TextView tvLevel;

    //测试分数统计图
    private BarChart barChart;
    //知识点饼状图
    private PieChart mPieChart;
    //知识点目标维度雷达图
    private RadarChart radarChart;

    //展示饼状图标签的列表
    private MyListView pieLv;

    //底部表格列表
    private MyListView mLv;
    private LinearLayout llContent;
    private RelativeLayout rlLoading;

    //页面数据模型
    private TestInfo.DataBean dataBean;

    private String exam_id;
    private String school_id;
    private String ttel;
    private String num;
    private String row_id2;

    //分数段柱状图的颜色取值
    private int[] colorIds = {R.color.tv_app_90, R.color.tv_app_80, R.color.tv_app_70, R.color.tv_app_60, R.color.tv_app_50};

    //模拟的服务器返回的json数据
    private String json = "{\"data\":{\"difficulty\":\"中等\",\"count_score\":\"6-5-4-8-13\",\"knowledge_percent\":\"其他-30_时态-12_动词-18_介词和介词短语-20_简单句-20\",\"R_class_amount\":\"28-36-98-25-12\",\"R_school_amount\":\"0-0-0-0-0\",\"avg_score\":104,\"R_amount\":\"词汇-70_句型结构-33_语法-65_阅读-35_交际能力-88\"},\"state\":200}";

    /**
     * 跳转到当前Activity的方法
     *
     * @return
     */
    public static void startActivity(Context context, String exam_id, String school_id, String ttel, String num, String row_id2) {
        Intent intent = new Intent(BaseApplication.context,TkTeacherAppraisalTestPaperActivity.class);
        intent.putExtra("exam_id", exam_id);
        intent.putExtra("school_id", school_id);
        intent.putExtra("ttel", ttel);
        intent.putExtra("num", num);
        intent.putExtra("row_id2", row_id2);
        context.startActivity(intent);
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_teacher_app_test_paper;
    }

    @Override
    protected void init() {
        showContent();

        //初始化视图
        initView();

        //获取传递参数
        initIntent();

        //配置雷达图的初始设置
        initRadarChart();

        //请求页面数据
        http();

    }


    /**
     * 获取传递参数
     */
    private void initIntent() {
        Intent intent = getIntent();
        exam_id = intent.getStringExtra("exam_id");
        school_id = intent.getStringExtra("school_id");
        ttel = intent.getStringExtra("ttel");
        num = intent.getStringExtra("num");
        row_id2 = intent.getStringExtra("row_id2");
    }


    /**
     * 请求
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "8");
        map.put("exam_id", exam_id);
        map.put("school_id", school_id);
        map.put("ttel", ttel);
        map.put("num", num);
        map.put("row_id2", row_id2);

        HttpUtils.post(HttpAdress.TESTPAPER, map, this, new HttpUtils.CallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                            rlLoading.setVisibility(View.GONE);
                        }
                        UiUtils.Toast(BaseApplication.ERROR, false);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                            rlLoading.setVisibility(View.GONE);
                        }

                        if (llContent != null && llContent.getVisibility() == View.GONE) {
                            llContent.setVisibility(View.VISIBLE);
                        }


                        if (!TextUtils.isEmpty(response)) {
                            TestInfo info = null;

                            Log.i("test", response);
                            try {
                                info = GsonUtil.jsonToBean(response, TestInfo.class);
//                                info = GsonUtil.jsonToBean(json, TestInfo.class);
                            } catch (Exception e) {
                                Log.i("test", Constants.PARSEDATAERROR);
                            }
                            if (null != info) {
                                if (200 == info.getState() || 103 == info.getState()) {
                                    //返回成功
                                    dataBean = info.getData();
                                    if (dataBean != null) {
                                        //分别设置数据
                                        //设置平均分
                                        tvScore.setText(dataBean.getAvg_score() + " 分");

                                        //设置难度
                                        tvLevel.setText(dataBean.getDifficulty() + "");

                                        //初始化测试分数统计图,柱状图的数据
                                        initBarChartData(dataBean.getCount_score());

                                        //初始化知识点图的饼状图数据
                                        initPieChartData(dataBean.getKnowledge_percent());

                                        //初始化班级整体语言知识目标维度图'
                                        initRadarChartData();

                                        //设置底部表格的数据
                                        initBottomLv();
                                    }
                                } else {
                                    UiUtils.Toast(Constants.ERRORSTATE + info.getState(), false);
                                    Log.i("test", Constants.ERRORSTATE + info.getState());
                                }

                            } else {
                                Log.i("test", Constants.EMPTY);
                            }

                        } else {
                            Log.i("test", Constants.EMPTY);
                        }

                    }
                }
        );
    }


    /**
     * 初始化视图
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tvTitle = findViewById(R.id.tv_title);
        tvScore = findViewById(R.id.tv_score);
        tvLevel = findViewById(R.id.tv_level);
        barChart = findViewById(R.id.barchart);
        mPieChart = findViewById(R.id.mPieChart);
        pieLv = findViewById(R.id.lvPic);
        mLv = findViewById(R.id.mlv);
        llContent = findViewById(R.id.ll_content);
        rlLoading = findViewById(R.id.rl_loading);
        rlLoading.setVisibility(View.GONE);
        radarChart = findViewById(R.id.radarChart);
    }

    /**
     * 初始化测试分数统计图
     */
    private void initBarChartData(String count_score) {

        if (TextUtils.isEmpty(count_score)) {
            return;
        }

        //获取所有分数段的人数
        String[] numArrays = count_score.split("-");
        int[] nums = new int[numArrays.length];
        for (int i = 0; i < numArrays.length; i++) {
            nums[i] = Integer.parseInt(numArrays[i]);
        }
        //计算人数的最大值
        int maxYValue = getMaxValue(nums) + 6;

        //Y轴上的Lable标签数
        int yLabelCount = 6;


        //初始化方法
        // 数据描述
//        Description description = new Description();
//        description.setText("全班成绩分布图");
//        description.setTextSize(10f);
        barChart.setDescription(null);
        // 如果没有数据的时候，会显示这个，类似ListView的EmptyView
        barChart.setNoDataText("没有图表数据，请添加");
        //禁止图表一切交互
        barChart.setTouchEnabled(true);
        // 是否显示表格颜色
        barChart.setDrawGridBackground(false);
        // 设置是否可以触摸
        barChart.setTouchEnabled(false);
        // 是否可以拖拽
        barChart.setDragEnabled(false);
        // 是否可以缩放
        barChart.setScaleEnabled(false);
        // 集双指缩放
        barChart.setPinchZoom(false);
        // 设置背景
        barChart.setBackgroundColor(Color.TRANSPARENT);
        // 如果打开，背景矩形将出现在已经画好的绘图区域的后边。
        barChart.setDrawGridBackground(false);
        // 集拉杆阴影
        barChart.setDrawBarShadow(false);
        // 图例
        barChart.getLegend().setEnabled(false);
        barChart.setFitBars(false);
        //设置图表周边间距
        barChart.setMinOffset(26f);
        //设置最小高度从0开始
        barChart.setMinimumHeight(0);
        // 隐藏右边的坐标轴
        barChart.getAxisRight().setEnabled(false);
        // 默认显示左边的左边轴
        barChart.getAxisLeft().setEnabled(true);
        // 设置数据
        barChart.animateX(2000);
        //设置图表周围边距
//        barChart.setMinOffset(20f);
        barChart.setExtraBottomOffset(0f);


        final ArrayList<String> xValue = new ArrayList<>();
        xValue.add("90分以上");
        xValue.add("80分至89分");
        xValue.add("70至79分");
        xValue.add("60至69分");
        xValue.add("低于60分");

        // y轴的数据集合和颜色
        //设置数据方法
        int co = nums.length;
        int[] colors = new int[co];

        ArrayList<BarEntry> yValues = new ArrayList<>();

        for (int i = 0; i < nums.length; i++) {
            yValues.add(new BarEntry(i, nums[i]));
            colors[i] = getResources().getColor(colorIds[i]);
        }
        YAxis yAxis = barChart.getAxisLeft();
        yAxis.setAxisMinimum(0);
        yAxis.setAxisMaximum(maxYValue);//设置Y轴上的最大值
        yAxis.setLabelCount(yLabelCount);//设置Y轴上的标签数
        yAxis.setTextColor(getResources().getColor(R.color.tvblack));
        yAxis.setTextSize(12f);

        //设置X轴的数据，需要重新设置其格式，才能显示你自定义的项，Y轴同理
        XAxis xAxis = barChart.getXAxis();
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                int n = (int) value;
                return xValue.get(n);
            }
        });

        xAxis.setLabelRotationAngle(-45);//设置x轴字体显示角度
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置X轴的位置TOP, BOTTOM, BOTH_SIDED, TOP_INSIDE, BOTTOM_INSIDE
        xAxis.setDrawGridLines(false);//回执网格线
        xAxis.setLabelCount(xValue.size() - 1);
        xAxis.setTextColor(getResources().getColor(R.color.tvblack));
        xAxis.setTextSize(10f);
        barChart.animateY(1000); // 立即执行的动画

        Legend mLegend = barChart.getLegend(); // 设置比例图标示
        mLegend.setForm(Legend.LegendForm.CIRCLE);//设置窗体样式
        mLegend.setFormSize(12f); //字体
        mLegend.setTextSize(12f);
        mLegend.setXEntrySpace(10);
        mLegend.setWordWrapEnabled(true);
        mLegend.setTextColor(getResources().getColor(R.color.tvblack));// 字体颜色


        BarDataSet dataSet = new BarDataSet(yValues, "");
        dataSet.setColors(colors);
        //设置每项柱状图的顶点的数值颜色
        dataSet.setValueTextColor(getResources().getColor(R.color.tvblack));


        //绘制所有 DataSets 数据对象包含的数据的值文本
        BarData barData = new BarData(dataSet);
        barData.setDrawValues(true);
        barData.setValueTextSize(10f);
        barData.setBarWidth(0.6f);
        barData.setValueTextColor(getResources().getColor(R.color.tvblack));
        //设置y轴显示的标签
        barData.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return ((int) (value)) + "";
            }
        });

        barChart.fitScreen();
        barChart.setData(barData);
        barChart.invalidate();

    }

    /**
     * 初始化知识点图的饼状图数据
     */
    private void initPieChartData(String knowledge_percent) {
        if (TextUtils.isEmpty(knowledge_percent)) {
            return;
        }
        PieChartManager pieChartManager = new PieChartManager(mPieChart, this);


        Integer[] pieColors = {getResources().getColor(R.color.tv_app_one), getResources().getColor(R.color.tv_app_two),
                getResources().getColor(R.color.tv_app_three), getResources().getColor(R.color.tv_app_four)
                , getResources().getColor(R.color.tv_app_five)
        };


        //先用下划线切割
        String[] outArrays = knowledge_percent.split("_");
        if (outArrays == null || outArrays.length == 0) {
            return;
        }

        //构建试卷难易程度的饼状图数据
        //各版块的名称
        List<String> names = new ArrayList<>();

        //各版块的百分比占比
        List<Float> perents = new ArrayList<>();
        List<Integer> colors = new ArrayList<>();

        //计算总的数量
        int total = getToalNum(outArrays);

        for (int i = 0; i < outArrays.length; i++) {
            String data = outArrays[i];
            String[] split = data.split("-");
            names.add(split[0]);
            perents.add((float) MathUtil.deciMal(Integer.parseInt(split[1]), total, 3));
            colors.add(pieColors[i]);
        }

        //各版本颜色占比
        pieChartManager.setPieChart(names, perents, colors);

        //设置饼状图的标签的列表数据
        List<PieInfo> pieInfos = new ArrayList<>();
        for (int i = 0; i < names.size(); i++) {
            PieInfo info = new PieInfo();
            info.colorId = colors.get(i);
            info.lable = names.get(i);
            pieInfos.add(info);
        }

        PieLvAdapter pieLvAdapter = new PieLvAdapter(this, pieInfos, R.layout.teacher_class_item_lv_pie);
        pieLv.setAdapter(pieLvAdapter);

    }

    /**
     * 获取饼状图的总的计量比
     *
     * @param outArrays
     * @return
     */
    private int getToalNum(String[] outArrays) {
        int res = 0;
        for (int i = 0; i < outArrays.length; i++) {
            String data = outArrays[i];
            String[] split = data.split("-");
            res += Integer.parseInt(split[1]);
        }
        return res;
    }


    /**
     * 初始化班级整体语言知识目标维度图
     */
    private void initRadarChart() {

        radarChart.setBackgroundColor(getResources().getColor(R.color.transparent));
        //是否开启描述
        radarChart.getDescription().setEnabled(false);
        // 绘制线条宽度，圆形向外辐射的线条
        radarChart.setWebLineWidth(1f);
        //设置各连接点到中心点的连接线的颜色
//        radarChart.setWebColor(Color.RED);
        // 内部线条宽度，外面的环状线条
        radarChart.setWebLineWidthInner(1f);
        //设置所有连接线条的颜色
        radarChart.setWebColorInner(getResources().getColor(R.color.tvgray));
        // 所有线条WebLine透明度
        radarChart.setWebAlpha(100);
        //是否可以拖动旋转
//        radarChart.setTouchEnabled(false);
        radarChart.setRotationEnabled(false);

        radarChart.animateXY(1000, 1000);

        YAxis yAxis = radarChart.getYAxis();
        // Y坐标轴标签个数
        yAxis.setLabelCount(5, false);
        // Y坐标值字体大小
        yAxis.setTextSize(9f);
        yAxis.setTextColor(getResources().getColor(R.color.tvblack));
        // Y坐标值的最小值
        yAxis.setAxisMinimum(0f);
        //Y坐标的最大值
        yAxis.setAxisMaximum(80f);
        //是否绘制Y轴上的值
        yAxis.setDrawLabels(true);
        yAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return (int) value + " %";
            }
        });


        XAxis xAxis = radarChart.getXAxis();
        // X坐标值字体大小
        xAxis.setTextSize(9f);
        //X轴字体偏移量
        xAxis.setYOffset(0f);
        xAxis.setXOffset(0f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {

            private String[] mActivities = new String[]{"词汇", "句型结构", "语法", "阅读", "交际能力"};

            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return mActivities[(int) value % mActivities.length];
            }
        });
        xAxis.setTextColor(getResources().getColor(R.color.tvblack));


        Legend l = radarChart.getLegend();
        // 图例位置
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        //隐藏Lengend
        l.setEnabled(false);
        // 图例X间距
        l.setXEntrySpace(7f);
        // 图例Y间距
        l.setYEntrySpace(5f);
        l.setTextColor(Color.WHITE);
    }

    /**
     * 设置雷达图的数据
     */
    public void initRadarChartData() {

        if (TextUtils.isEmpty(dataBean.getR_class_amount())) {
            return;
        }
        String[] dataArrays = dataBean.getR_class_amount().split("-");
        if (null == dataArrays || dataArrays.length == 0) {
            return;
        }

        List<Float> values = new ArrayList<>();
        for (int i = 0; i < dataArrays.length; i++) {
            values.add(Float.parseFloat(dataArrays[i]));
        }

        // 设置各个连接点的数据
        ArrayList<RadarEntry> entries = new ArrayList<>();

        if (values == null || values.size() == 0) {
            return;
        }

        for (int i = 0; i < values.size(); i++) {
            entries.add(new RadarEntry(values.get(i)));
        }

        RadarDataSet set = new RadarDataSet(entries, "");
        set.setColor(getResources().getColor(R.color.tv_app_rader_color));
        //设置内部连接区域的区域颜色值
        set.setFillColor(Color.rgb(103, 110, 129));
        set.setDrawFilled(true);
        set.setFillAlpha(180);
        //设置内部连接线的线条宽度
        set.setLineWidth(1f);
        set.setDrawHighlightCircleEnabled(true);
        set.setDrawHighlightIndicators(false);

        ArrayList<IRadarDataSet> sets = new ArrayList<>();
        sets.add(set);

        RadarData data = new RadarData(sets);
        data.setValueTextSize(8f);
        //是否绘制内部每个点的维度数据
        data.setDrawValues(false);
        data.setValueTextColor(Color.WHITE);

        radarChart.setData(data);
        radarChart.invalidate();
    }


    /**
     * 设置底部表格列表的数据
     */
    private void initBottomLv() {

        if (null == dataBean) {
            return;
        }
        String r_amount = dataBean.getR_amount();
        if (TextUtils.isEmpty(r_amount)) {
            return;
        }
        //维度名称
        List<String> names = new ArrayList<>();
        //题数
        List<String> nums = new ArrayList<>();

        String[] nameAndNums = r_amount.split("_");
        if (null == nameAndNums || nameAndNums.length == 0) {
            return;
        }

        for (int i = 0; i < nameAndNums.length; i++) {
            String[] strings = nameAndNums[i].split("-");
            names.add(strings[0]);
            nums.add(strings[1]);
        }


        //全班正确率
        List<String> classDatas = new ArrayList<>();
        String r_class_amount = dataBean.getR_class_amount();
        if (TextUtils.isEmpty(r_class_amount)) {
            return;
        }
        String[] split = r_class_amount.split("-");
        if (null == split || split.length == 0) {
            return;
        }
        for (int i = 0; i < split.length; i++) {
            classDatas.add(split[i]);
        }

        //全校正确率
        List<String> schoolDatas = new ArrayList<>();
        String r_school_amount = dataBean.getR_school_amount();
        if (TextUtils.isEmpty(r_school_amount)) {
            return;
        }
        String[] schoolPresents = r_school_amount.split("-");
        if (null == schoolPresents || schoolPresents.length == 0) {
            return;
        }
        for (int i = 0; i < schoolPresents.length; i++) {
            schoolDatas.add(schoolPresents[i]);
        }

        List<ContentInfo> oldDatas = new ArrayList<>();
        for (int i = 0; i < names.size(); i++) {
            ContentInfo info = new ContentInfo();
            info.zsd = names.get(i);
            info.ts = nums.get(i);
            info.qbzql = classDatas.get(i);
            info.qxzql = schoolDatas.get(i);
            oldDatas.add(info);
        }

        ContentLvAdapter adapter = new ContentLvAdapter(this, oldDatas, R.layout.teacher_app_lv_item_content);
        mLv.setAdapter(adapter);
    }


    /**
     * 计算Int数组的最大值
     */
    public int getMaxValue(int[] array) {
        int maxIndex = array[0];
        for (int i = 0; i < array.length; i++) {
            if (maxIndex < array[i]) {
                maxIndex = array[i];
            }
        }
        return maxIndex;
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        }
    }
}
